package com.sinoglobal.sinostore.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.sinoglobal.sinostore.R;
import com.sinoglobal.sinostore.StateBaseActivity;
import com.sinoglobal.sinostore.adapter.AddressAdapter;
import com.sinoglobal.sinostore.bean.AddressListVo;
import com.sinoglobal.sinostore.bean.AddressVo;
import com.sinoglobal.sinostore.bean.BaseVo;
import com.sinoglobal.sinostore.dialog.ShopDialogStyle2;
import com.sinoglobal.sinostore.dialog.ShopDialogStyle2.ShopDialogStyle1Listener;
import com.sinoglobal.sinostore.system.Constants;

import java.util.ArrayList;
import java.util.List;

import andbase.view.pullview.AbPullListView;

/**
 * 
 * @author lk
 * @createdate 2014-9-9 下午2:19:34
 * @Description: TODO(收货地址列表)
 */
public class AddressListActivity extends StateBaseActivity implements OnItemLongClickListener, OnClickListener, ShopDialogStyle1Listener,
		OnItemClickListener {
	private AbPullListView listView;
	private AddressAdapter adapter;
	private AddressVo addressVo;
	private ImageView addAddress;// 添加收货地址按钮

	private LinearLayout noaddress;// 没有收货地址的布局
	private LinearLayout advert;// 广告位
	private ImageButton btnClosdAd;// 关闭广告按钮
	private int addressCount = 0;

	private ShopDialogStyle2 dialogStyle2;

	public static final String ADDRESS = "address";
	public static final String ORDER = "submitOrder";
	public String orderSubmit = "";
	private String addressId;
	private List<AddressVo> addresss;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shop_activity_addresslist);
		openChenJInShi();
		titleView.setText("管理收货地址");
		// 设置添加按钮
		templateButtonRight.setVisibility(View.VISIBLE);
		templateButtonRight.setBackgroundDrawable(getResources().getDrawable(R.drawable.shop_title_btn_add));
		titleRightText.setVisibility(View.GONE);
		templateButtonRight.setOnClickListener(this);
		templateButtonLeft.setOnClickListener(this);
		adapter = new AddressAdapter(this, new ArrayList<AddressVo>());
		// 初始化控件
		initView();

		orderSubmit = getIntent().getStringExtra("orderSubmit");
		addressId = getIntent().getStringExtra("addressId");
	}

	/**
	 * 
	 * @author lk
	 * @createdate 2014-9-9 下午2:27:47
	 * @Description: (初始化控件)
	 * 
	 */
	private void initView() {
		// 没有收货地址的布局
		noaddress = (LinearLayout) this.findViewById(R.id.noaddress);
		// 添加收货地址按钮
		addAddress = (ImageView) this.findViewById(R.id.img_add_btn);
		advert = (LinearLayout) this.findViewById(R.id.advertview);
		// btnClosdAd = (ImageButton)this.findViewById(R.id.adrert_ibtn);

		listView = (AbPullListView) this.findViewById(R.id.listView1);
		listView.setDivider(null);
		listView.setPullLoadEnable(false);
		listView.setPullRefreshEnable(false);
		listView.setAdapter(adapter);
		listView.setEmptyView(noaddress);
		noaddress.setVisibility(View.GONE);
		// 长按点击事件
		listView.setOnItemLongClickListener(this);
		addAddress.setOnClickListener(this);
		listView.setOnItemClickListener(this);

	}

	@Override
	protected void onResume() {
		super.onResume();
		getData();
	}

	/**
	 * 
	 * @author lk
	 * @createdate 2014-9-21 下午2:42:18
	 * @Description: (获取用户收货地址的数据)
	 * 
	 */
	private void getData() {
		final ProgressDialog dialog = new ProgressDialog(AddressListActivity.this);
		dialog.setMessage("加载中...");
		try {
			dialog.show();
		} catch (Exception e) {
		}
		HttpUtils httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("por", "5001");
		params.addQueryStringParameter("user_id", Constants.userCenterId);
		params.addQueryStringParameter("proIden", Constants.STOREFLAG);
		httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				try {
					dialog.dismiss();
				} catch (Exception e) {
				}
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				try {
					dialog.dismiss();
				} catch (Exception e) {
				}
				String result = responseInfo.result;
				if (!TextUtils.isEmpty(result)) {
					AddressListVo entity = JSON.parseObject(result, AddressListVo.class);
					if (null == entity) {
						return;
					}
					if (Constants.STORE_SUCCESS_CODE.equals(entity.getCode())) {
						adapter.clearData();
						addressCount = entity.getList().size();
						if (addressCount > 0) {
							// 显示地址列表
							listView.setVisibility(View.VISIBLE);
							// 隐藏没有收货地址布局
							templateButtonRight.setVisibility(View.VISIBLE);
							addresss = entity.getList();
							adapter.addList(entity.getList());
						} else {
							// 隐藏头部添加按钮
							templateButtonRight.setVisibility(View.INVISIBLE);
							listView.setVisibility(View.GONE);
							addresss = null;
						}
						if (ORDER.equals(orderSubmit) && adapter.getCount() > Constants.selectAddress) {
							adapter.setItemSelect(Constants.selectAddress);
						}
					} else {
						templateButtonRight.setVisibility(View.INVISIBLE);
						noaddress.setVisibility(View.VISIBLE);
						listView.setVisibility(View.GONE);
					}
					noaddress.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3) {
		// 获取选中item的地址对象
		addressVo = adapter.getItem(position - 1);
		dialogStyle2 = new ShopDialogStyle2(AddressListActivity.this, "", "", "删除地址", "设为默认");
		dialogStyle2.show();
		return true;
	}

	@Override
	public void onClick(View view) {
		Intent intent = null;
		int id = view.getId();
		if (id == R.id.shop_title_but_right) {
			if (addressCount >= 10) {
				showShortToast("收货地址已达上限~");
				return;
			}
			intent = new Intent(this, SelAddressActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		} else if (id == R.id.img_add_btn) {
			intent = new Intent(this, SelAddressActivity.class);
			startActivity(intent);// 跳转到添加收货地址页面
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		} else if (id == R.id.shop_title_but_left) {
			addAddress();
		} else {

		}
	}

	// 删除地址
	public void confirm() {
		if (null != addressId && addressId.equals(addressVo.getId())) {
			showShortToast("当前使用地址不可删除");
		} else {
			setDeleteOrDefault("1", addressVo.getId());
		}
	}

	// 设为默认
	public void cancel() {
		setDeleteOrDefault("2", addressVo.getId());
	}

	private void setDeleteOrDefault(final String action, String id) {
		final ProgressDialog dialog = new ProgressDialog(AddressListActivity.this);
		dialog.setMessage("设置中...");
		try {
			dialog.show();
		} catch (Exception e) {
		}
		HttpUtils httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("por", "5003");
		params.addQueryStringParameter("user_id", Constants.userCenterId);
		params.addQueryStringParameter("id", id);
		params.addQueryStringParameter("action", action);
		params.addQueryStringParameter("proIden", Constants.STOREFLAG);
		httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params, new RequestCallBack<String>() {
			@Override
			public void onFailure(HttpException arg0, String arg1) {
				try {
					dialog.dismiss();
				} catch (Exception e) {
				}
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				try {
					dialog.dismiss();
				} catch (Exception e) {
				}
				String result = responseInfo.result;
				if (!TextUtils.isEmpty(result)) {
					BaseVo entity = JSON.parseObject(result, BaseVo.class);
					if (null == entity) {
						return;
					}
					if (Constants.STORE_SUCCESS_CODE.equals(entity.getCode())) {
						// 操作成功重新加载数据
						getData();
						// 设置默认
						if ("2".equals(action)) {
							showShortToast("修改成功");
						} else {
							showShortToast("删除成功");
						}
					}
				}
			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// 判断是否是从下订单页面跳转过来的
		if (ORDER.equals(orderSubmit)) {
			adapter.setItemSelect(position - 1);
			Constants.selectAddress = position - 1;
			Intent intent = new Intent();
			intent.putExtra(ADDRESS, adapter.getItem(position - 1));
			setResult(SubmitOrderFormActivity.ISAddRESS, intent);
			finish();
		}
	}

	private void addAddress() {
		if (ORDER.equals(orderSubmit)) {
			if (null != addresss) {
				for (int i = 0; i < addresss.size(); i++) {
					if (Constants.selectAddress == i) {
						Intent intent = new Intent();
						intent.putExtra(ADDRESS, addresss.get(i));
						setResult(SubmitOrderFormActivity.ISAddRESS, intent);
						finish();
						return;
					}
				}
			}
		}
		this.finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			addAddress();
			return false;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
}
